package controller;

import jakarta.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.StorageRecord;
import pojo.Supplier;
import pojo.SysUser;
import service.StorageRecordService;
import service.SupplierService;
import utils.Constants;
import utils.PageSupport;


import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/storageRecord")
public class StorageRecordController {
    private static Logger log=Logger.getLogger(StorageRecordController.class);

    @Resource
    private StorageRecordService storageRecordService;

    @Resource
    private SupplierService supplierService;

    @GetMapping("/list")
    public String list(Model model, String queryGoodsName,
                       String queryPayStatus, Integer querySupplierId,
                       @RequestParam(defaultValue = "1")Integer pageIndex){
        System.out.println("queryGoodsName:"+queryGoodsName);
        System.out.println("queryPayStatus:"+queryPayStatus);
        System.out.println("querySupplierId:"+querySupplierId);
        System.out.println("pageIndex:"+pageIndex);

        List<StorageRecord> storageRecordList=null;
        try{
            int pageSiz= Constants.pageSize;
            int totalCount=storageRecordService.selectCount(queryGoodsName,queryPayStatus,querySupplierId);
            PageSupport pages=new PageSupport();
            pages.setNumberPage(pageSiz);
            pages.setCurrentPage(pageIndex-1);
            pages.setTotalPage(totalCount);

            int totalPageCount=pages.getTotalPage();
            if(pageIndex>totalPageCount){
                pageIndex=totalCount;
                throw new RuntimeException("页面不正确");
            }
            storageRecordList=storageRecordService.selectPage(queryGoodsName,queryPayStatus,querySupplierId,pages.getCurrentPage()*pageSiz,pages.getNumberPage());
            model.addAttribute("userList",storageRecordList);
            List<Supplier> supplierList=supplierService.selectAllSuppliers();
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("storageRecordList",storageRecordList);
            model.addAttribute("querypayStatus",queryPayStatus);
            model.addAttribute("querySupplierId",querySupplierId);
            model.addAttribute("queryGoodsName",queryGoodsName);
            // 总页数
            model.addAttribute("totalPageCount",totalPageCount);
            // 总记录数
            model.addAttribute("totalCount",totalCount);
            // 当前页数
            model.addAttribute("currentPageNo",pageIndex);
        }catch (Exception e){
            log.error("查询入库记录列表失败",e);
            return "redirect:/sys/user/toSysError";
        }
        return "storageRecord/list";
    }

    @GetMapping("/view/{storageRecordId}")
    public String view(@PathVariable Integer storageRecordId,Model model){
        System.out.println("storageRecordId:"+storageRecordId);
        StorageRecord storageRecord=null;
        try{
            storageRecord=storageRecordService.selectById(storageRecordId);
            model.addAttribute("storageRecord",storageRecord);
        }catch (Exception e){
            log.error("查询入库记录失败",e);
            return "redirect:/sys/user/toSysError";
        }
        return "storageRecord/view";
    }

    @GetMapping("/toAdd")
    public String toAdd(){

        return "storageRecord/add";
    }

    @PostMapping("/add")
    public String add(StorageRecord storageRecord, HttpSession session){
        System.out.println("入库记录："+storageRecord);
        SysUser user=(SysUser) session.getAttribute(Constants.USER_SESSION);
        try{
            storageRecord.setCreatedTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            storageRecord.setCreatedUserId(user.getId());
            boolean add = storageRecordService.add(storageRecord);
            System.out.println("入库记录添加："+add);
        }catch (RuntimeException e){
            log.error("添加入库记录失败",e);
            return "redirect:/sys/user/toSysError";
        }
        return "redirect:/sys/storageRecord/list";
    }

    @GetMapping("/toUpdate/{storageRecordId}")
    public String toUpdate(@PathVariable Integer storageRecordId,Model model){
        System.out.println("storageRecordId:"+storageRecordId);
        StorageRecord storageRecord=null;
        try{
            storageRecord=storageRecordService.selectById(storageRecordId);
            model.addAttribute("storageRecord",storageRecord);
        }catch (RuntimeException e){
            log.error("查询入库记录失败",e);
            return "redirect:/sys/user/toSysError";
        }
        return "storageRecord/update";
    }

     @PostMapping("/update")
     public String update(StorageRecord storageRecord, HttpSession session){
         System.out.println("入库记录："+storageRecord);
         SysUser user=(SysUser) session.getAttribute(Constants.USER_SESSION);
         try{
             storageRecord.setUpdatedTime(new Date());
             storageRecord.setUpdatedUserId(user.getId());
             boolean update = storageRecordService.update(storageRecord);
             System.out.println("入库记录修改："+update);
         }catch (RuntimeException e){
             log.error("修改入库记录失败",e);
             return "redirect:/sys/user/toSysError";
         }
         return "redirect:/sys/storageRecord/list";
     }

     @ResponseBody
     @DeleteMapping("/del/{storageRecordId}")
     public Object del(@PathVariable Integer storageRecordId){
         System.out.println("入库记录id："+storageRecordId);
         Map<String,Object> map=new HashMap<>();
         try{
             boolean del = storageRecordService.delete(storageRecordId);
             map.put("delResult",del?"true":"false");
             System.out.println("入库记录删除："+del);
         }catch (RuntimeException e){
             log.error("删除入库记录失败",e);
             map.put("delResult","notexist");
         }
         return map;
     }
}
